package com.rzgeo.wcgallay.comp;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.GeodatabaseFeatureTable;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.Symbol;
import com.rzgeo.wcgallay.R;
import com.rzgeo.wcgallay.model.ElvInfo;
import com.rzgeo.wcgallay.util.WcmUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhanghang on 2017/12/12.
 */

public class WcmReseDetail extends LinearLayout {

    private SeekBar _sbGauge;
    private Spinner _spSetElv;

    private GeodatabaseFeatureTable _elv2info;
    private TextView _txvHighElv;
    private TextView _txvLowElv;
    private TextView _txvElv;
    private WcmValueTxv _txvVolume;
    private WcmValueTxv _txvArea2d;
    private WcmValueTxv _txvArea3d;
    private SeekBar.OnSeekBarChangeListener _onSeekBarChanged=new SeekBar.OnSeekBarChangeListener() {

        public Symbol _symbol;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if(_elvInfos==null||_elvInfos.size()==0)
            {
                WcmUtil.Dialog.ShowMsg(getContext(),"请选中一个库体部分后再操作",null);
                return;
            }
            ElvInfo elvInfo = _elvInfos.get(progress);
            _graphicsOverlay.getGraphics().clear();
            _graphicsOverlay.getGraphics().add(new Graphic(elvInfo.geometry,getSymbol()));

            _txvElv.setText(Float.toString(elvInfo.elv));
            _txvVolume.setValue(elvInfo.volume, WcmUtil.Const.VolumeUtils,1,false);
            _txvArea2d.setValue(elvInfo.area2d, WcmUtil.Const.AreaUtils,1,false);
            _txvArea3d.setValue(elvInfo.area3d, WcmUtil.Const.AreaUtils,1,false);

            if(_onDetail!=null)
                _onDetail.onElvChanged(_elvInfos,progress);

            if(_spSetElv.getSelectedItemPosition()!=progress)
                _spSetElv.setSelection(_elvInfos.size()-1-progress);
        }



        private Symbol getSymbol() {
            if(_symbol==null){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    _symbol=new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getContext().getColor(R.color.wcmWaterTrans),
                            new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID,Color.YELLOW,1.0f));
                }else{
                    _symbol=new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, getContext().getResources().getColor(R.color.wcmWaterTrans),
                            new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID,Color.YELLOW,1.0f));
                }
            }
            return _symbol;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };
    private ArrayList<ElvInfo> _elvInfos =new ArrayList<>();
    private Comparator<? super ElvInfo> _comparator=new Comparator<ElvInfo>() {
        @Override
        public int compare(ElvInfo o1, ElvInfo o2) {
            if(o1.elv<o2.elv)
                return -1;
            else if(o1.elv>o2.elv)
                return 1;
            else
                return 0;
        }
    };
    private GraphicsOverlay _graphicsOverlay;

    private AniHolder _aniHolder;
    private AdapterView.OnItemSelectedListener _onSetElvSelect=new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(_elvInfos==null||_elvInfos.size()==0)
            {
                WcmUtil.Dialog.ShowMsg(getContext(),"请选中一个库体部分后再操作",null);
                return;
            }

            int i=_elvInfos.size()-1-position;
            if(_sbGauge.getProgress()!=i) {
                _sbGauge.setProgress(i);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    };
    private OnDetail _onDetail;

    private class AniHolder
    {
        private final SeekBar _sbStep;
        private Timer _timer;
        private ImageButton _btnPrevious;
        private ImageButton _btnRew;
        private ImageButton _btnPlayPause;
        private ImageButton _btnFF;
        private ImageButton _btnNext;

        private boolean isPlaying=false;

        public Drawable _drawPause;
        public Drawable _drawPlay;

        public AniHolder(){
//            _timer = new Timer();

            _btnPrevious=findViewById(R.id.btn_previous);
            _btnRew=findViewById(R.id.btn_rew);
            _btnPlayPause=findViewById(R.id.btn_play_pause);
            _btnFF=findViewById(R.id.btn_ff);
            _btnNext=findViewById(R.id.btn_next);

            _sbStep=findViewById(R.id.sb_step);

            _btnPlayPause.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if(isPlaying){
                        isPlaying=false;
                        stopPlay();
                    }else{
                        isPlaying=true;
                        startPlay();
                    }
                }
            });

            _btnPrevious.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    setElvSelect(0);
                }
            });

            _btnNext.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    setElvSelect(_elvInfos.size()-1);
                }
            });

//            _btnRew.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    _sbGauge.setProgress(_elvInfos.size()-1);
//                }
//            });
//
//            _btnFF.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    _sbGauge.setProgress(_elvInfos.size()-1);
//                }
//            });

        }


        private void startPlay() {
            if(_sbGauge.getProgress()==(_elvInfos.size()-1)){
                setElvSelect(0);
            }
            _timer=new Timer();
            _timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message( );
                    message.what = 1;
                    _handler.sendMessage(message);
                }
            }, 0, (_sbStep.getProgress()+1) * 250);
            _sbStep.setEnabled(false);

            if(_drawPause==null)
                _drawPause= getContext().getResources().getDrawable(android.R.drawable.ic_media_pause);
            _btnPlayPause.setImageDrawable(_drawPause);

            _btnPrevious.setEnabled(false);
            _btnNext.setEnabled(false);
        }

        private void stopPlay() {

            if(_drawPlay==null)
                _drawPlay= getContext().getResources().getDrawable(android.R.drawable.ic_media_play);
            _btnPlayPause.setImageDrawable(_drawPlay);
            _btnPrevious.setEnabled(true);
            _btnNext.setEnabled(true);

            if(_timer!=null)
            _timer.cancel();
            _timer=null;

            _sbStep.setEnabled(true);
        }

        public class TimerHandel extends Handler {

            public void handleMessage(Message msg) {

                switch (msg.what) {

                    case 1:

                        int progress=_sbGauge.getProgress();
                        if(progress<_elvInfos.size()-1){
                            setElvSelect(progress+1);
                        }else{
                            stopPlay();
                        }
                        break;

                }

                super.handleMessage(msg);

            }
        };

        private TimerHandel _handler = new TimerHandel();
    }

    private void setElvSelect(int index) {
        _sbGauge.setProgress(index);
        _spSetElv.setSelection(_elvInfos.size()-1-index);

    }

    public WcmReseDetail(Context context) {
        super(context);
    }

    public WcmReseDetail(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public WcmReseDetail(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        _sbGauge=findViewById(R.id.sb_gauge);
        _spSetElv=findViewById(R.id.sp_set_elv);


        _txvHighElv=findViewById(R.id.txv_high_elv);
        _txvLowElv=findViewById(R.id.txv_low_elv);

        //水位信息
        _txvElv=findViewById(R.id.txv_elv);
        _txvVolume=findViewById(R.id.txv_volume);
        _txvArea2d=findViewById(R.id.txv_area_2d);
        _txvArea3d=findViewById(R.id.txv_area_3d);

        //动画控件
        _aniHolder=new AniHolder();

        _sbGauge.setOnSeekBarChangeListener(_onSeekBarChanged);
        _spSetElv.setOnItemSelectedListener(_onSetElvSelect);
    }

    public interface OnDetail{
        void onElvChanged(ArrayList<ElvInfo> elv, int iElv);
    }

    public void setup(GeodatabaseFeatureTable elv2info, GraphicsOverlay graphicsOverlay, final int currentElv, OnDetail onDetail) {
        _elv2info=elv2info;
        _onDetail=onDetail;
        _graphicsOverlay=graphicsOverlay;
        if(_elv2info==null){
            setElvSelect(0);
            _sbGauge.setEnabled(false);
            _spSetElv.setEnabled(false);

            _txvHighElv.setText("0");
            _txvLowElv.setText("0");
            _txvHighElv.setText("0");

            _txvElv.setText("0");
            _txvVolume.setText("0");
            _txvArea2d.setText("0");
            _txvArea3d.setText("0");
        }else{
            final ListenableFuture<FeatureQueryResult> fr = _elv2info.queryFeaturesAsync(new QueryParameters());
            fr.addDoneListener(new Runnable() {
                @Override
                public void run() {
                    try {
                        _elvInfos.clear();

                        FeatureQueryResult fq = fr.get();

                        Iterator<Feature> iterator = fq.iterator();
                        Map<String,String>fieldMap=new HashMap<>();
                        for(Field f:fq.getFields()){
                            if(f.getName().endsWith("Plane_Height")){
                                fieldMap.put("Plane_Height",f.getName());
                            }
                            else if(f.getName().endsWith("Volume")){
                                fieldMap.put("Volume",f.getName());
                            }
                            else if(f.getName().endsWith("Area_2D")){
                                fieldMap.put("Area_2D",f.getName());
                            }
                            else if(f.getName().endsWith("Area_3D")){
                                fieldMap.put("Area_3D",f.getName());
                            }
                        }

                        while (iterator.hasNext()) {
                            Feature feature = iterator.next();
                            Map<String, Object> attrs = feature.getAttributes();
                            ElvInfo info = new ElvInfo(
                                    WcmUtil.Convert.Float(attrs.get(fieldMap.get("Plane_Height"))),
                                    WcmUtil.Convert.Float(attrs.get(fieldMap.get("Volume"))),
                                    WcmUtil.Convert.Float(attrs.get(fieldMap.get("Area_2D"))),
                                    WcmUtil.Convert.Float(attrs.get(fieldMap.get("Area_3D"))),
                                    feature.getGeometry()
                            );
                            _elvInfos.add(info);
                        }

                        Collections.sort(_elvInfos,_comparator);

                        _sbGauge.setMax(_elvInfos.size()-1);

                        String[]titles=new String[_elvInfos.size()];
                        for(int i=0;i<_elvInfos.size();i++){
                            titles[_elvInfos.size()-i-1]=Float.toString(_elvInfos.get(i).elv);
                        }

                        _spSetElv.setAdapter(new ArrayAdapter<>(
                                getContext(),
                                android.R.layout.simple_spinner_dropdown_item,
                                titles));

                        _txvHighElv.setText(Float.toString(_elvInfos.get(_elvInfos.size()-1).elv));
                        _txvLowElv.setText(Float.toString(_elvInfos.get(0).elv));

                        _sbGauge.setEnabled(true);
                        _spSetElv.setEnabled(true);

                        if(currentElv>-1)
                            setElvSelect(currentElv);
                        else
                            setElvSelect(0);
//                        setElvSelect(_elvInfos.size()-1);

                    } catch (Exception e){

                    }
                }
            });

        }
    }
}
